﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FriendsNearby.Services;
using FriendsNearby.Services.Facebook;

namespace FacebookNamesImporter
{
    class Program
    {
        static void Main(string[] args)
        {
            var importer = new Importer(new FriendsNearbySystem());
            if (args.Length > 0)
            {
                var ids = args.Select(a => new Guid(a));
                importer.Import(ids);
            }
            else
            {
                importer.ImportAllUsers();
            }
            Console.WriteLine("FacebookNamesImporter finished successfully.");
            Console.WriteLine("Press any to key continue...");
            Console.ReadLine();
        }
    }

    public class Importer
    {
        IUsersService userService;
        FacebookSocialNetworkService socialNetworkService;

        public Importer(IServiceProvider system)
        {
            userService = system.GetService<IUsersService>();
            socialNetworkService = system.GetService<ISocialNetworkService, FacebookSocialNetworkService>();
        }

        public void ImportAllUsers()
        {
            Import(new List<Guid>(userService.GetAllUsers()));
        }

        public void Import(IEnumerable<Guid> ids)
        {
            foreach (var id in ids)
            {
                Import(id);
            }
        }

        public void Import(Guid userID)
        {
            var reg = userService.QueryUserRegistry(r => r.UserID == userID);
            try
            {
                socialNetworkService.EnsureFacebookUserExists(reg.FacebookUserId, reg.FacebookSessionKey);
            }
            catch
            {
                Console.WriteLine("Error importing UserID:{0} FacebookUserID:{1}", reg.UserID, reg.FacebookUserId);
            }
        }
    }
}
